package com.allwees.sender;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.CollectionUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * 邮件服务
 *
 * @author jy2016
 *
 */
@Slf4j
public class EMailSender {

	private JavaMailSender sender;

	private String from;

	private String personal;

	@Async
	public void send(String to, String title, String content, boolean html) {
		_send(to, title, content, html, null, null);
	}

	@Async
	public void send(String to, String title, String content, boolean html, Map<String, String> params) {
		_send(to, title, content, html, null, null);
	}

	private void _send(String to, String subject, String content, boolean html, String[] attachmentFilePaths, Map<String,String> rscMap) {
		MimeMessage message = sender.createMimeMessage();

		try {
			// true表示需要创建一个multipart message
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			try {
				helper.setFrom(from, personal);
			} catch(UnsupportedEncodingException e) {
			}
			helper.setTo(to);
			helper.setSubject(subject);
			helper.setText(content, html);

			// 添加附件
			addAttachment(helper, attachmentFilePaths);

			// 添加嵌入
			addInline(helper,rscMap);

			sender.send(message);
			log.info("发送邮件[{}]成功.", to);
		} catch(MailException | MessagingException e) {
			log.error("发送邮件失败！", e);
		}
	}

	private void addInline(MimeMessageHelper helper, Map<String,String> rscMap) throws MessagingException {
		if (CollectionUtils.isEmpty(rscMap)) {
			return;
		}
		for (String key : rscMap.keySet()) {
			FileSystemResource res = new FileSystemResource(new File(key));
			helper.addInline(rscMap.get(key), res);
		}
	}

	private void addAttachment(MimeMessageHelper helper, String[] attachmentFilePaths) throws MessagingException {
		if (ArrayUtils.isEmpty(attachmentFilePaths)) {
			return;
		}
		for (String filePath : attachmentFilePaths) {
			FileSystemResource file = new FileSystemResource(new File(filePath));
			String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
			helper.addAttachment(fileName, file);
		}
	}

	public void setSender(JavaMailSender sender) {
		this.sender = sender;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public void setPersonal(String personal) {
		this.personal = personal;
	}
}
